import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useNotebookStore = defineStore('notebook', () => {
  // 笔记数据
  const notes = ref([])
  
  // 当前选中的分类
  const currentCategory = ref('all')
  
  // 分类列表
  const categories = ref([
    { id: 'all', name: '全部', color: '#409EFF' },
    { id: 'tcm', name: '中医知识', color: '#67C23A' },
    { id: 'herbs', name: '中药方剂', color: '#E6A23C' },
    { id: 'diagnosis', name: '诊断方法', color: '#F56C6C' },
    { id: 'treatment', name: '治疗方法', color: '#909399' },
    { id: 'personal', name: '个人笔记', color: '#9C27B0' }
  ])

  // 根据分类筛选笔记
  const filteredNotes = computed(() => {
    if (currentCategory.value === 'all') {
      return notes.value
    }
    return notes.value.filter(note => note.category === currentCategory.value)
  })

  // 添加笔记
  const addNote = (note) => {
    const newNote = {
      id: Date.now(),
      title: note.title || '无标题',
      content: note.content || '',
      category: note.category || 'personal',
      type: note.type || 'text', // text, image, audio
      mediaUrl: note.mediaUrl || '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    notes.value.unshift(newNote)
    saveToLocalStorage()
  }

  // 更新笔记
  const updateNote = (id, updates) => {
    const index = notes.value.findIndex(note => note.id === id)
    if (index !== -1) {
      notes.value[index] = { ...notes.value[index], ...updates, updatedAt: new Date().toISOString() }
      saveToLocalStorage()
    }
  }

  // 删除笔记
  const deleteNote = (id) => {
    const index = notes.value.findIndex(note => note.id === id)
    if (index !== -1) {
      notes.value.splice(index, 1)
      saveToLocalStorage()
    }
  }

  // 设置当前分类
  const setCurrentCategory = (category) => {
    currentCategory.value = category
  }

  // 保存到本地存储
  const saveToLocalStorage = () => {
    localStorage.setItem('notebook-notes', JSON.stringify(notes.value))
  }

  // 从本地存储加载
  const loadFromLocalStorage = () => {
    const saved = localStorage.getItem('notebook-notes')
    if (saved) {
      notes.value = JSON.parse(saved)
    }
  }

  // 初始化时加载数据
  loadFromLocalStorage()

  return {
    notes,
    currentCategory,
    categories,
    filteredNotes,
    addNote,
    updateNote,
    deleteNote,
    setCurrentCategory
  }
}) 